const db = require('../../../db/index');
const myDate = require('../../tool/myDate');
const arrMethod = require('../../tool/arrMethod');
const mysql = require('mysql');

exports.addAttendance = () => {
	// 获取现在的年月 xxxx-xx
	let dateObj = new Date();
	const arrMonth = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
	// 本年本月
	const dateStr = myDate.yearMonth(dateObj.getFullYear(), arrMonth[dateObj.getMonth()]);
	// 本年本月的上一月
	let dateYear = dateObj.getFullYear();
	let lastMonth = dateObj.getMonth() - 1;
	if (lastMonth < 0) {
		lastMonth = 11;
		dateYear - 1;
	};
	const lastDateStr = myDate.yearMonth(dateYear, arrMonth[lastMonth]);
	// 本年本月的下一月
	let nextMonth = dateObj.getMonth() + 1;
	if (nextMonth > 11) {
		nextMonth = 0;
		dateYear + 1;
	};
	const nextDateStr = myDate.yearMonth(dateYear, arrMonth[nextMonth]);
	// 查询考勤初始天数
	const sql = 'select * from initial';
	db.query(sql, (err, results) => {
		const init_day = results[0].init_day;
		const rest_day = results[0].rest_day;
		// 查询 工资表里 是否已经有 本月工资数据
		const sql = 'select * from salary where s_date=?';
		db.query(sql, dateStr, (err, results) => {
			// 如果没有数据，且今天是15号，则新增一条，如果有数据则选择更新数据
			if (results.length == 0 && dateObj.getDate() == init_day) {
				const toDay = myDate.toDay();
				// 查出今天的考勤记录
				const sql = 'select * from attendance where day_date=?';
				db.query(sql, toDay, (err, results) => {
					// 获取本轮考勤天数
					let s_all_day = myDate.getMonthDay(dateStr);
					// 创建arr，从考勤记录添加用户id，部门id，岗位id，并添加本轮考勤天数
					let arr = results.map((item) => {
						return Object.assign(
							{},
							{ s_user_id: item.user_id },
							{ s_department_id: item.department_id },
							{ s_position_id: item.position_id },
							{ s_all_day }
						)
					})
					// 从user表中添加每个人当时的岗位工资
					const sql = 'select * from user';
					db.query(sql, (err, results) => {
						for (let j = 0 ; j < arr.length ; j++){
							for (let i = 0 ; i < results.length ; i++){
								if(arr[j].s_user_id === results[i].id){
									if (results[i].state === 0){
										arr[j].s_post_salary = results[i].try_out_money
									} else {
										arr[j].s_post_salary = results[i].official_salary
									}
								}
							}
						}
						// 从考勤表里查出本月的数据
						const sql = "select * from attendance where date_format(day_date, '%Y-%m')=?";
						db.query(sql, dateStr, (err, results) => {
							// 剔除掉15号前的数据 (将符合条件的数组节点替换为只剩下一个id)
							for (let i = 0, len = results.length; i < len; i++) {
								let str = results[i].day_date;
								if (str.substring(8, 10) < init_day) {
									results[i] = {
										user_id: results[i].user_id,
									};
								}
							}
							let thisMonthArr = results
							// 查出下个月的考勤表数据
							const sql = "select * from attendance where date_format(day_date, '%Y-%m')=?";
							db.query(sql, nextDateStr, (err, results) => {
								// 剔除掉15号后的考勤数据
								for (let i = 0, len = results.length; i <
									len; i++) {
									let str = results[i].day_date;
									if (str.substring(8, 10) >= init_day) {
										results[i] = {
											user_id: results[i].user_id
										};
									}
								}
								let nextMonthArr = results;
								// 将本月和下个月数据合并为一个
								let attendanceData = [...nextMonthArr, ...thisMonthArr];
								// 计算各类天数
								for (let i = 0; i < arr.length; i++) {
									let s_office_day = 0;
									let s_rest_day = 0;
									let s_overtime_day = 0;
									for (let j = 0; j < attendanceData.length; j++) {
										if (arr[i].s_user_id === attendanceData[j].user_id) {
											if (attendanceData[j].office_status === 0) {
												s_office_day++;
											}
											if (attendanceData[j].office_status === 1) {
												s_rest_day++;
											}
											if (attendanceData[j].overtime_status === 1) {
												s_overtime_day = s_overtime_day + attendanceData[j].overtime_time;
											}
											Object.defineProperty(arr[i], 's_office_day', {
												value: s_office_day,
												writable: true,
												enumerable: true,
												configurable: true
											});
											Object.defineProperty(arr[i], 's_rest_day', {
												value: s_rest_day,
												writable: true,
												enumerable: true,
												configurable: true
											});
											Object.defineProperty(arr[i], 's_overtime_day', {
												value: s_overtime_day,
												writable: true,
												enumerable: true,
												configurable: true
											})
										};
									}
									arr[i].s_date = dateStr
								}
								arr = arrMethod.mysqlArr(arr);
								const sql = "insert into salary(s_user_id, s_department_id, s_position_id, s_all_day, s_post_salary, s_office_day, s_rest_day, s_overtime_day, s_date) values ?";
								db.query(sql, [arr], (err, results) => {
									console.log(err)
									console.log('本月份工资表添加成功', dateStr)
								});
							})
						})
					})
				});
			} else {
				// 如果当前天数大于等于15，就更新这组数据
				if (dateObj.getDate() >= init_day) {
					// 拿到需要更新数据 工资表id
					const sql = 'select * from salary where s_date=?';
					db.query(sql, dateStr, (err, results) => {
						let arr = results;
						// 准备 需要的数据 从考勤表里查出本月的数据
						const sql = "select * from attendance where date_format(day_date, '%Y-%m')=?";
						db.query(sql, dateStr, (err, results) => {
							// 剔除掉15号前的数据(将符合条件的数组节点替换为只剩下一个id)
							for (let i = 0, len = results.length; i < len; i++) {
								let str = results[i].day_date;
								if (str.substring(8, 10) < init_day) {
									results[i] = {
										user_id: results[i].user_id
									};
								}
							}
							let thisMonthArr = results
							// 查出下个月的考勤表数据
							const sql = "select * from attendance where date_format(day_date, '%Y-%m')=?";
							db.query(sql, nextDateStr, (err, results) => {
								// 剔除掉15号后的数据
								for (let i = 0, len = results.length; i < len; i++) {
									let str = results[i].day_date;
									if (str.substring(8, 10) >= init_day) {
										results[i] = {
											user_id: results[i].user_id
										};
									}
								}
								let nextMonthArr = results;
								// 将本月和下个月数据合并为一个
								let attendanceData = [...nextMonthArr, ...thisMonthArr];
								// 计算各类天数
								for (let i = 0; i < arr.length; i++) {
									let s_office_day = 0;
									let s_rest_day = 0;
									let s_overtime_day = 0;
									for (let j = 0; j < attendanceData.length; j++) {
										if (arr[i].s_user_id === attendanceData[j].user_id) {
											if (attendanceData[j].office_status === 0) {
												s_office_day++;
											}
											if (attendanceData[j].office_status === 1) {
												s_rest_day++;
											}
											if (attendanceData[j].overtime_status === 1) {
												s_overtime_day =
													s_overtime_day +
													attendanceData[j]
													.overtime_time;
											}
											Object.defineProperty(arr[i], 's_office_day', {
													value: s_office_day,
													writable: true,
													enumerable: true,
													configurable: true
												});
											Object.defineProperty(arr[i], 's_rest_day', {
													value: s_rest_day,
													writable: true,
													enumerable: true,
													configurable: true
												});
											Object.defineProperty(arr[i], 's_overtime_day', {
													value: s_overtime_day,
													writable: true,
													enumerable: true,
													configurable: true
												})
										};
									}
								}
								// 处理 arr 的数据
								let values = [];
								arr.forEach(function(n, i) {
									values.push([n, n.s_id])
								})
								const model_sql = 'update salary set ? where s_id=?';
								let sqls = '';
								// 拼接sql语句
								values.forEach((item, index) => {
									sqls += mysql.format(model_sql, item) + ';'
								})
								db.query(sqls, (err, results) => {
									console.log('本月工资表更新成功', dateStr)
								})
							})
						})
					})
				};
				// 如果当前天数小于15，就更新这组数据
				if (dateObj.getDate() < init_day) {
					// 拿到需要更新数据 工资表id
					const sql = 'select * from salary where s_date=?';
					db.query(sql, lastDateStr, (err, results) => {
						let arr = results;
						// 准备 需要的数据 从考勤表里查出本月的数据
						const sql =
							"select * from attendance where date_format(day_date, '%Y-%m')=?";
						db.query(sql, dateStr, (err, results) => {
							// 剔除掉本月十五号后的数据
							for (let i = 0, len = results.length; i < len; i++) {
								let str = results[i].day_date;
								if (str.substring(8, 10) >= init_day) {
									results[i] = {
										user_id: results[i].user_id
									};
								}
							}
							let thisMonthArr = results;
							// 准备 需要的数据 从考勤表里查出上个月的数据
							const sql ="select * from attendance where date_format(day_date, '%Y-%m')=?";
							db.query(sql, lastDateStr, (err, results) => {
								// 剔除掉上个月15号前数据
								for (let i = 0, len = results.length; i <
									len; i++) {
									let str = results[i].day_date;
									if (str.substring(8, 10) < init_day) {
										results[i] = {
											user_id: results[i].user_id
										};
									}
								}
								let lastMonthArr = results;
								// 将本月和上月的数据合为一个
								let attendanceData = [...lastMonthArr, ...
									thisMonthArr
								];
								// 计算各类天数
								for (let i = 0; i < arr.length; i++) {
									let s_office_day = 0;
									let s_rest_day = 0;
									let s_overtime_day = 0;
									for (let j = 0; j < attendanceData
										.length; j++) {
										if (arr[i].s_user_id ===
											attendanceData[j].user_id) {
											if (attendanceData[j]
												.office_status === 0) {
												s_office_day++;
											}
											if (attendanceData[j]
												.office_status === 1) {
												s_rest_day++;
											}
											if (attendanceData[j]
												.overtime_status === 1) {
												s_overtime_day =
													s_overtime_day +
													attendanceData[j]
													.overtime_time;
											}
											Object.defineProperty(arr[i],
												's_office_day', {
													value: s_office_day,
													writable: true,
													enumerable: true,
													configurable: true
												});
											Object.defineProperty(arr[i],
												's_rest_day', {
													value: s_rest_day,
													writable: true,
													enumerable: true,
													configurable: true
												});
											Object.defineProperty(arr[i],
												's_overtime_day', {
													value: s_overtime_day,
													writable: true,
													enumerable: true,
													configurable: true
												})
										};
									}
								}
								// 处理 arr 的数据
								let values = [];
								arr.forEach(function(n, i) {
									values.push([n, n.s_id])
								})
								const model_sql =
									'update salary set ? where s_id=?';
								let sqls = '';
								// 拼接sql语句
								values.forEach((item, index) => {
									sqls += mysql.format(model_sql,
										item) + ';'
								})
								db.query(sqls, (err, results) => {
									console.log('上月工资表更新成功', lastDateStr)
								})
							})
						})
					})
				}
			}
		})
	})
}